package com.caigou.service.impl;

import com.caigou.bean.bid.entity.Region;
import com.caigou.bean.es.EsBid;
import com.caigou.bean.vo.BidVO;
import com.caigou.component.RedisComponent3;
import com.caigou.mapper.bid.BidMapper;
import com.caigou.mapper.bid.RegionMapper;
import com.caigou.repository.EsBidRepository;
import com.caigou.service.IBidService;
import com.caigou.util.DateUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class BidServiceImpl implements IBidService {
    @Resource
    private BidMapper bidMapper;
    @Resource
    private EsBidRepository esBidRepository;
    @Resource
    private RedisComponent3 redisComponent3;
    @Resource
    private RegionMapper bidRegionMapper;
    /**
     * list列表相关标讯（除去本条标讯）
     */
    @Override
    public List<BidVO> listRelativeBid(Long bidId, String projectCode, int size) {
        //从ES中搜索
        //Optional<EsBid> esBid = esBidService.findById(bidId.toString());
        if (StringUtils.isEmpty(projectCode)) {
            return Collections.emptyList();
        }
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        qb.must(QueryBuilders.matchPhraseQuery("projectCode", projectCode));
        Iterable<EsBid> esBidsIterable = esBidRepository.search(qb);
        List<BidVO> esBids = new ArrayList<>();


        esBidsIterable.forEach(bean -> {
            if (!String.valueOf(bidId).equals(bean.getId())) {
                BidVO bidVO = new BidVO();
                BeanUtils.copyProperties(bean, bidVO);
                bidVO.setId(bean.getId());
                bidVO.setProjectDate(DateUtil.dateToString(bean.getProjectDate(), "yyyy-MM-dd HH:mm:ss"));
                if (esBids.size() <= size) {
                    esBids.add(bidVO);
                }
            }
        });


        //return bidMapper.listRelativeBid(bidId, projectCode, size);
        return esBids;
    }

    /**
     * based on 地区编码==》获取地区信息
     */
    public Region getBidRegionByRegionCode(String regionCode) {
        String key = "bidRegion:regionCode:" + regionCode;
        Region bidRegion = (Region) redisComponent3.get(key);
        if (bidRegion == null) {
            bidRegion = bidRegionMapper.getRegionByRegionCode(regionCode);
            if (bidRegion != null) {
                redisComponent3.set(key, bidRegion, 24 * 60 * 60);//缓存24小时
            }
        }
        return bidRegion;
    }
}
